package models

import (
	"errors"
	"fmt"

	"reflect"
	"strings"
	"time"

	// "github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

// WatchHistory 观看历史
type WatchHistory struct {
	Id        string    `orm:"column(id);pk"`
	UserId    string    `orm:"column(user_id)"`
	VideoId   string    `orm:"column(vid_id)"`
	VideoName string    `orm:"column(video_name)"`
	OrgId     string    `orm:"column(organization_id)"`
	OrgName   string    `orm:"column(org_name)"`
	DeptId    string    `orm:"column(dept_id)"`
	DeptName  string    `orm:"column(dept_name)"`
	UserName  string    `orm:"column(user_name)"`
	Url       string    `orm:"column(url)"`
	LookTime  time.Time `orm:"column(looktime)"`
	LookLong  int64     `orm:"column(looklong)"`
	Type      int64     `orm:"column(type)"`
	Status    int64     `orm:"column(status)"`
	Isdelete  int64     `orm:"column(isdelete)"`
	Ctime     time.Time `orm:"column(ctime);type(timestamp with time zone)"`
	Creater   string    `orm:"column(creater)"`
	Utime     time.Time `orm:"column(utime);type(timestamp with time zone)"`
	Updater   string    `orm:"column(updater)"`
	LookCount int       `orm:"column(lookcount)"`
}

func (t *WatchHistory) TableName() string {
	return "vid_watchhistory"
}

func init() {
	orm.RegisterModel(new(WatchHistory))
}

// AddWatchHistory 添加观看记录
func AddWatchHistory(m *WatchHistory) (err error) {
	o := orm.NewOrm()
	_, err = o.Insert(m)
	return
}

// GetWatchHistoryById 获取观看记录
func GetWatchHistoryById(id string) (v *WatchHistory, err error) {
	o := orm.NewOrm()
	v = &WatchHistory{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

//GetAllWatchHistory 获取所有观看记录
func GetAllWatchHistory(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(WatchHistory))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []WatchHistory
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

// DeleteWatchHistory 删除观看记录
func DeleteWatchHistory(id string) (err error) {
	o := orm.NewOrm()
	v := WatchHistory{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&WatchHistory{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

// GetHistoryByVideoId 根据视频获取相关观看记录
func GetHistoryByVideoId(id int64, vtype int64) (WatchHistory, error) {
	o := orm.NewOrm()
	var wh WatchHistory
	err := o.Raw("select * from vid_watchhistory where vid_id=? and type=?", id, vtype).QueryRow(&wh)
	return wh, err
}

//GetHistoryByUserIdAndUrl 根据用户与视频Url获取观看记录
//Param userId 用户id
//Param url 视频播放地址
//return WatchHistory, error
func GetHistoryByUserIdAndUrl(userId int64, url string) (WatchHistory, error) {
	o := orm.NewOrm()
	var wh WatchHistory
	err := o.QueryTable(new(WatchHistory)).Filter("user_id", userId).Filter("url", url).One(&wh)
	return wh, err
}
